<template>
  <div>
    <el-form :inline="true">
      <el-form-item>
        <el-input
          v-model="searchForm.deviceName"
          placeholder="设备名称"
          clearable
        >
        </el-input>
      </el-form-item>

      <el-form-item>
        <el-input
          v-model="searchForm.deviceCode"
          placeholder="设备编号"
          clearable
        >
        </el-input>
      </el-form-item>

      <el-form-item>
        <el-select v-model="searchForm.status" placeholder="设备状态">
          <el-option label="全部" :value="''"></el-option>
          <el-option label="正常" :value="1"></el-option>
          <el-option label="维修中" :value="2"></el-option>
          <el-option label="报废" :value="3"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button @click="get_device_list">搜索</el-button>
        <el-button @click="handle_reset">重置</el-button>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          @click="dialog_visible = true"
          v-has="'device:list:add'"
          >新增</el-button
        >
      </el-form-item>
    </el-form>

    <el-table
      :data="tableData"
      tooltip-effect="dark"
      style="width: 100%"
      border
      stripe
    >

      <el-table-column prop="id" label="设备ID"> </el-table-column>
      <el-table-column prop="deviceCode" label="设备编号"> </el-table-column>
      <el-table-column prop="deviceName" label="设备名称"> </el-table-column>
      <el-table-column prop="deviceType" label="设备类型"> </el-table-column>
      <el-table-column prop="location" label="设备位置"> </el-table-column>
      <el-table-column prop="installDate" label="安装日期"> </el-table-column>
      <el-table-column prop="status" label="设备状态">
        <template slot-scope="scope">
          <el-tag size="small" v-if="scope.row.status === 1" type="success"
            >正常</el-tag
          >
          <el-tag size="small" v-else-if="scope.row.status === 2" type="warning"
            >维修中</el-tag
          >
          <el-tag size="small" v-else-if="scope.row.status === 3" type="danger"
            >报废</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column prop="manufacturer" label="生产厂商"> </el-table-column>
      <el-table-column prop="description" label="设备描述"> </el-table-column>
      <el-table-column label="操作" width="250">
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="detail_handle(scope.row.id)"
            v-has="'device:list:detail'"
            >详情</el-button
          >
          <el-divider direction="vertical"></el-divider>

          <el-button
            type="text"
            @click="edit_handle(scope.row.id)"
            v-has="'device:list:edit'"
            >编辑</el-button
          >
          <el-divider direction="vertical"></el-divider>

          <template>
            <el-popconfirm
              title="确定删除吗？"
              @confirm="del_handle(scope.row.id)"
            >
              <el-button
                type="text"
                slot="reference"
                v-has="'device:list:delete'"
                >删除</el-button
              >
            </el-popconfirm>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      @size-change="handle_size_change"
      @current-change="handle_current_change"
      layout="total, sizes, prev, pager, next, jumper"
      :page-sizes="[10, 20, 50, 100]"
      :current-page="pageNum"
      :page-size="pageSize"
      :total="total"
    >
    </el-pagination>

    <!--新增对话框-->
    <el-dialog
      title="设备信息"
      :visible.sync="dialog_visible"
      width="600px"
      :before-close="handle_close"
    >
      <el-form :model="edit_form" :rules="edit_form_rules" ref="edit_form">
        <el-form-item label="设备编号" prop="deviceCode" label-width="120px">
          <el-input
            v-model="edit_form.deviceCode"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item label="设备名称" prop="deviceName" label-width="120px">
          <el-input
            v-model="edit_form.deviceName"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item label="设备类型" prop="deviceType" label-width="120px">
          <el-input
            v-model="edit_form.deviceType"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item label="设备位置" prop="location" label-width="120px">
          <el-input v-model.trim="edit_form.location" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="所属部门" prop="departmentId" label-width="120px">
            <el-select v-model="edit_form.departmentId" placeholder="请选择部门">
              <el-option
                v-for="dept in departmentList"
                :key="dept.id"
                :label="dept.name"
                :value="dept.id"
              ></el-option>
            </el-select>
          </el-form-item>

        <el-form-item label="安装日期" prop="installDate" label-width="120px">
          <el-date-picker
            v-model="edit_form.installDate"
            type="date"
            placeholder="选择日期"
          ></el-date-picker>
        </el-form-item>

        <el-form-item label="生产厂商" prop="manufacturer" label-width="120px">
          <el-input
            v-model="edit_form.manufacturer"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item label="规格型号" prop="model" label-width="120px">
          <el-input v-model.trim="edit_form.model" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="设备状态" prop="status" label-width="120px">
          <el-select v-model="edit_form.status" placeholder="请选择状态">
            <el-option label="正常" :value="1"></el-option>
            <el-option label="维修中" :value="2"></el-option>
            <el-option label="报废" :value="3"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="设备描述" prop="description" label-width="120px">
          <el-input
            v-model="edit_form.description"
            type="textarea"
            rows="3"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="reset_form('edit_form')">取 消</el-button>
        <el-button type="primary" @click="submit_form('edit_form')"
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <!--详情对话框-->
    <el-dialog title="设备详情" :visible.sync="detail_visible" width="600px">
      <el-form :model="detail_form" label-width="120px">
        <el-form-item label="设备编号">
          <span>{{ detail_form.deviceCode }}</span>
        </el-form-item>
        <el-form-item label="设备名称">
          <span>{{ detail_form.deviceName }}</span>
        </el-form-item>
        <el-form-item label="设备类型">
          <span>{{ detail_form.deviceType }}</span>
        </el-form-item>
        <el-form-item label="设备位置">
          <span>{{ detail_form.location }}</span>
        </el-form-item>
        <el-form-item label="所属部门">
          <span>{{ detail_form.departmentName || "-" }}</span>
        </el-form-item>
        <el-form-item label="安装日期">
          <span>{{ detail_form.installDate }}</span>
        </el-form-item>
        <el-form-item label="生产厂商">
          <span>{{ detail_form.manufacturer || "-" }}</span>
        </el-form-item>
        <el-form-item label="规格型号">
          <span>{{ detail_form.model || "-" }}</span>
        </el-form-item>
        <el-form-item label="设备状态">
          <el-tag size="small" v-if="detail_form.status === 1" type="success"
            >正常</el-tag
          >
          <el-tag
            size="small"
            v-else-if="detail_form.status === 2"
            type="warning"
            >维修中</el-tag
          >
          <el-tag
            size="small"
            v-else-if="detail_form.status === 3"
            type="danger"
            >报废</el-tag
          >
        </el-form-item>
        <el-form-item label="设备描述">
          <span>{{ detail_form.description || "-" }}</span>
        </el-form-item>
        <el-form-item label="创建时间">
          <span>{{ detail_form.created }}</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detail_visible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import deviceApi from "@/api/device.js";
import repairApi from "@/api/repair-request.js";
import sysDeptApi from "@/api/sys-dept.js";
export default {
  name: "DeviceList",
  data() {
    return {
      searchForm: {},

      total: 0,
      pageSize: 10,
      pageNum: 1,
      departmentList: [],
      departmentTree: [],

      dialog_visible: false,
      detail_visible: false,
      edit_form: {
        id: "",
        deviceCode: "",
        deviceName: "",
        deviceType: "",
        location: "",
        installDate: "",
        status: 1,
        departmentId: "",
        manufacturer: "",
        model: "",
        description: "",
      },
      detail_form: {},

      tableData: [],

      edit_form_rules: {
        deviceCode: [
          { required: true, message: "请输入设备编号", trigger: "blur" },
        ],
        deviceName: [
          { required: true, message: "请输入设备名称", trigger: "blur" },
        ],
        deviceType: [
          { required: true, message: "请输入设备类型", trigger: "blur" },
        ],
        location: [
          { required: true, message: "请输入设备位置", trigger: "blur" },
        ],
        status: [
          { required: true, message: "请选择设备状态", trigger: "blur" },
        ],
        departmentId: [
          { required: true, message: "请选择所属部门", trigger: "blur" },
        ],
        installDate: [
          { required: true, message: "请选择安装日期", trigger: "blur" },
        ],
        manufacturer: [
          { required: false, message: "请输入生产厂商", trigger: "blur" },
        ],
        model: [
          { required: false, message: "请输入规格型号", trigger: "blur" },
        ],
        description: [
          { required: false, message: "请输入设备描述", trigger: "blur" },
        ],
      },


    };
  },
  created() {
    this.get_device_list();
    this.get_department_list();
  },
  methods: {
    get_department_list() {
      sysDeptApi.tree().then(res => {
        this.departmentList = res.data || [];
        this.departmentTree = res.data || [];
      }).catch(error => {
        console.error('获取部门列表失败:', error);
      });
    },
    handle_size_change(val) {
      this.pageSize = val;
      this.get_device_list();
    },
    handle_current_change(val) {
      this.pageNum = val;
      this.get_device_list();
    },

    reset_form(formName) {
      if (this.$refs[formName]) {
        this.$refs[formName].resetFields();
      }
      this.dialog_visible = false;
      this.edit_form = {
        id: "",
        deviceCode: "",
        deviceName: "",
        deviceType: "",
        location: "",
        installDate: "",
        status: 1,
        departmentId: "",
        manufacturer: "",
        model: "",
        description: "",
      };
    },
    handle_close() {
      this.reset_form("edit_form");
    },

    get_device_list() {
      deviceApi
        .list({
          deviceName: this.searchForm.deviceName,
          deviceCode: this.searchForm.deviceCode,
          status: this.searchForm.status,
          page_num: this.pageNum,
          page_size: this.pageSize,
        })
        .then((res) => {
          this.tableData = res.data.records || [];
          this.pageSize = res.data.size;
        this.pageNum = res.data.current;
          this.total = res.data.total;
        });
      repairApi
        .list({
          ...this.searchForm,
          page_num: this.pageNum,
          page_size: this.pageSize,
        })
        .then((res) => {
          if (res && res.data && res.data) {
            this.repairList = res.data.records || [];
            this.pageSize = res.data.size || this.pageSize;
            this.pageNum = res.data.current || this.pageNum;
          } else {
            this.repairList = [];
          }
        })
        .catch((error) => {
          console.error("获取工单列表失败:", error);
          this.repairList = [];
        });
    },
    // 重置搜索条件
    handle_reset() {
      this.searchForm = {};
      this.get_device_list();
    },

    submit_form(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 确保时间格式正确
          const formData = {
            ...this.edit_form, // 修正变量名，使用正确的表单变量
            updatedAt: new Date(),
          };
          if (!formData.id) {
            formData.createdAt = new Date();
          }
          const api = formData.id ? deviceApi.update : deviceApi.add;
          api(formData).then((res) => {
            this.$message({
              showClose: true,
              message: "操作成功",
              type: "success",
              onClose: () => {
                // 代码移到下一行
              },
            });
            this.get_device_list();
            this.dialog_visible = false;
          });
        } else {
          return false;
        }
      });
    },
    edit_handle(id) {
      deviceApi.detail(id).then((res) => {
        // 确保字段名称匹配
        this.edit_form = {
          id: res.data.id,
          deviceCode: res.data.deviceCode,
          deviceName: res.data.deviceName,
          deviceType: res.data.deviceType,
          location: res.data.location,
          installDate: res.data.installDate,
          status: res.data.status,
          departmentId: res.data.departmentId,
          manufacturer: res.data.manufacturer,
          model: res.data.model,
          description: res.data.description,
        };
        this.dialog_visible = true;
      });
    },
    detail_handle(id) {
      deviceApi.detail(id).then((res) => {
        this.detail_form = res.data;
        this.detail_visible = true;
      });
    },
    del_handle(id) {
      const ids = id ? [id] : this.multiple_selection.map((row) => row.id);
      // 根据api文件，delete方法需要单个id，需要循环调用
      if (ids.length === 1) {
        deviceApi.delete(ids[0]).then(() => {
          this.$message({
            showClose: true,
            message: "操作成功",
            type: "success",
            onClose: () => {
              // 代码移到下一行
            },
          });
          this.get_device_list();
        });
      } else if (ids.length > 1) {
        // 对于多个id，使用Promise.all处理批量删除
        Promise.all(ids.map((itemId) => deviceApi.delete(itemId))).then(() => {
          this.$message({
            showClose: true,
            message: "批量删除成功",
            type: "success",
            onClose: () => {
              // 代码移到下一行
            },
          });
          this.get_device_list();
        });
      }
    },
  },
};
</script>

<style scoped>
.el-pagination {
  float: right;
  margin-top: 22px;
}
</style>